﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SimpleFeedBindingsLibrarySLTest
{
    public partial class MainPage : UserControl
    {
        private System.Collections.Generic.Dictionary<string, string> m_NamespaceDictionary = new System.Collections.Generic.Dictionary<string, string>();

        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.RunTests();
        }

        private void RunTests()
        {
            System.Collections.Generic.List<string> FeedContentsList = null;

            #region Feed Content Initialization

            string FeedContents1 = "<?xml version='1.0' encoding='utf-8'?>";
            FeedContents1 += " <rss version='2.0' xmlns:sx='http://feedsync.org/2007/feedsync' xmlns:sxn='http://feedsync.org/2008/namespaces/note' xmlns:sfb='http://feedsync.org/2008/namespaces/binding' xmlns:geo='http://www.w3.org/2003/01/geo/wgs84_pos#'>";
            FeedContents1 += "  <channel>";
            FeedContents1 += "   <title>Note With Geo Reference Feed</title>";
            FeedContents1 += "   <description>Use this feed as a template for your own solutions</description>";
            FeedContents1 += "   <link>http://example.com/notes</link>";
            FeedContents1 += "   <sfb:binding id='http://feedsync.org/2008/namespaces/note' name='Note With Geo' title='{sxn:subject}' description='&lt;table style=&apos;width: 100%&apos;&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Subject:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{sxn:subject}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Body:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{sxn:body}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Created:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{sxn:created}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Created By:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{sxn:createdBy}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Last Updated:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{sxn:lastUpdated}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Last Updated By:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{sxn:lastUpdatedBy}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Latitude:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{geo:lat}&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width=&apos;30%&apos;&gt;&lt;b&gt;Longitude:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;{geo:long}&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;'>";
            FeedContents1 += "    <sx:sync id='http://feedsync.org/2008/namespaces/note' updates='2'>";
            FeedContents1 += "     <sx:history sequence='2' by='Simple Feed Bindings Client' when='2008-02-20T00:04:20Z' />";
            FeedContents1 += "    </sx:sync>";
            FeedContents1 += "    <sfb:namespace localprefix='sxn' uri='http://feedsync.org/2008/namespaces/note' />";
            FeedContents1 += "    <sfb:namespace localprefix='geo' uri='http://www.w3.org/2003/01/geo/wgs84_pos#' />";
            FeedContents1 += "    <sfb:field element='sxn:subject' label='Subject' contenttype='text' type='none' required='true' />";
            FeedContents1 += "    <sfb:field element='sxn:body' label='Body' contenttype='text' type='none' required='true' multiline='true' />";
            FeedContents1 += "    <sfb:field element='sxn:created' label='Created' contenttype='text' type='datetime' required='true' />";
            FeedContents1 += "    <sfb:field element='sxn:createdBy' label='Created By' contenttype='text' type='none' required='true' />";
            FeedContents1 += "    <sfb:field element='sxn:lastUpdated' label='Last Updated' contenttype='text' type='datetime' />";
            FeedContents1 += "    <sfb:field element='sxn:lastUpdatedBy' label='Last Updated By' contenttype='text' type='none' />";
            FeedContents1 += "    <sfb:field element='geo:lat' label='Latitude' contenttype='text' type='floatingpoint' />";
            FeedContents1 += "    <sfb:field element='geo:long' label='Longitude' contenttype='text' type='floatingpoint' />";
            FeedContents1 += "   </sfb:binding>";
            FeedContents1 += "  </channel>";
            FeedContents1 += " </rss>";

            string FeedContents2 = "<?xml version='1.0' encoding='utf-8'?>";
            FeedContents2 += " <rss version='2.0' xmlns:sfb='http://feedsync.org/2008/namespaces/binding' xmlns:sx='http://feedsync.org/2007/feedsync'>";
            FeedContents2 += "   <channel>";
            FeedContents2 += "     <title>Namespace test</title>";
            FeedContents2 += "     <description>This is a Simple Feed Bindings test for multiple levels/combos of namespaced data</description>";
            FeedContents2 += "     <sfb:binding name='Namespace test' id='id1'>";
            FeedContents2 += "       <sx:sync id='ffcda1ba-5305-41d3-9ae7-ffc7efe08b85' updates='1'>";
            FeedContents2 += "         <sx:history sequence='1' when='2008-02-13T08:57:54Z' />";
            FeedContents2 += "       </sx:sync>";
            FeedContents2 += "       <sfb:namespace localprefix='y' uri='http://bogusYurl' />";
            FeedContents2 += "       <sfb:namespace localprefix='z' uri='http://bogusZurl' />";
            FeedContents2 += "       <sfb:field element='a' />";
            FeedContents2 += "       <sfb:field element='a/b' />";
            FeedContents2 += "       <sfb:field element='z:a' />";
            FeedContents2 += "       <sfb:field element='z:a/z:b' />";
            FeedContents2 += "       <sfb:field element='y:a/z:b' />";
            FeedContents2 += "       <sfb:field element='a/z:b' />";
            FeedContents2 += "       <sfb:field element='z:a/b' />";
            FeedContents2 += "       <sfb:field element='a/z:b/y:c' />";
            FeedContents2 += "       <sfb:field element='z:a/b/y:c' />";
            FeedContents2 += "       <sfb:field element='z:a/y:b/c' />";
            FeedContents2 += "     </sfb:binding>";
            FeedContents2 += "   </channel>";
            FeedContents2 += " </rss>";

            FeedContentsList = new System.Collections.Generic.List<string>(){FeedContents1, FeedContents2};

            #endregion

            System.Xml.Linq.XDocument XDocument = null;
            Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.BindingCollection BindingCollection = null;
            Microsoft.CSA.FeedSync.FeedSyncLibrarySL.RSSFeed RSSFeed = null;

            string Title;
            string Description;
            int Index = 0;

            foreach (string FeedContents in FeedContentsList)
            {
                ++Index;

                System.Windows.Controls.TreeViewItem ParentTreeViewItem = new System.Windows.Controls.TreeViewItem() { Header = "Feed " + Index };
                ParentTreeViewItem.KeyUp += TreeViewItem_KeyUp;
                ResultsTreeView.Items.Add(ParentTreeViewItem);

                #region TEST 1 - Read Binding

                try
                {
                    XDocument = System.Xml.Linq.XDocument.Parse(FeedContents);
                    RSSFeed = new Microsoft.CSA.FeedSync.FeedSyncLibrarySL.RSSFeed(XDocument);
                    BindingCollection = new Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.BindingCollection(RSSFeed);

                    this.DisplayTestResults
                        (
                        "Test 1 Results", 
                        XDocument,
                        ParentTreeViewItem
                        );
                }
                catch (System.Exception Exception)
                {
                    System.Diagnostics.Debug.Assert(false, "Exception in Test 1 - " + Exception.Message);
                }

                #endregion

                #region TEST 2 - Add new data instance

                try
                {
                    //  Use first binding for testing purposes
                    Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Binding Binding = BindingCollection.Bindings[0];

                    Microsoft.CSA.FeedSync.FeedSyncLibrarySL.RSSFeedSyncItem RSSFeedSyncItem = new Microsoft.CSA.FeedSync.FeedSyncLibrarySL.RSSFeedSyncItem
                        (
                        RSSFeed,
                        "SimpleFeedBindingsLibrarySLTest",
                        "FakeID123456789",
                        "TempTitle",
                        System.String.Empty
                        );


                    System.Collections.Generic.Dictionary<string, Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue> FieldValueSortedList = this.GetTestFieldValues
                        (
                        Binding,
                        out Title,
                        out Description
                        );

                    if (!System.String.IsNullOrEmpty(Title))
                        RSSFeedSyncItem.Title = Title;

                    if (!System.String.IsNullOrEmpty(Description))
                        RSSFeedSyncItem.Description = Description;

                    //  Add Binding identifier and set field values
                    System.Xml.Linq.XElement BindingXElement = Binding.CreateIdentifierXElement(BindingCollection);
                    RSSFeedSyncItem.XElement.Add(BindingXElement);

                    //  Create namespaced elements 
                    Binding.SetFieldValuesForXElement
                        (
                        RSSFeedSyncItem.XElement,
                        FieldValueSortedList
                        );

                    RSSFeed.AddItem(RSSFeedSyncItem);

                    this.DisplayTestResults
                        (
                        "Test 2 Results", 
                        XDocument,
                        ParentTreeViewItem
                        );
                }
                catch (System.Exception Exception)
                {
                    System.Diagnostics.Debug.Assert(false, "Exception in Test 2 - " + Exception.Message);
                }

                #endregion

                #region TEST 3 - Update an existing data instance

                try
                {
                    //  Use first binding for testing purposes
                    Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Binding Binding = BindingCollection.Bindings[0];

                    Microsoft.CSA.FeedSync.FeedSyncLibrarySL.RSSFeedSyncItem RSSFeedSyncItem = RSSFeed.GetItem("FakeID123456789");

                    System.Collections.Generic.Dictionary<string, Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue> FieldValueSortedList = this.GetTestFieldValues
                        (
                        Binding,
                        out Title,
                        out Description
                        );

                    if (!System.String.IsNullOrEmpty(Title))
                        RSSFeedSyncItem.Title = Title;

                    if (!System.String.IsNullOrEmpty(Description))
                        RSSFeedSyncItem.Description = Description;

                    //  Add Binding identifier and set field values
                    System.Xml.Linq.XElement BindingXElement = Binding.CreateIdentifierXElement(BindingCollection);
                    RSSFeedSyncItem.XElement.Add(BindingXElement);

                    //  Create namespaced elements 
                    Binding.SetFieldValuesForXElement
                        (
                        RSSFeedSyncItem.XElement,
                        FieldValueSortedList
                        );

                    RSSFeed.ReplaceItem("FakeID123456789", RSSFeedSyncItem);

                    this.DisplayTestResults
                        (
                        "Test 3 Results", 
                        XDocument,
                        ParentTreeViewItem
                        );
                }
                catch (System.Exception Exception)
                {
                    System.Diagnostics.Debug.Assert(false, "Exception in Test 3 - " + Exception.Message);
                }

                #endregion

                System.Threading.Thread.Sleep(500);
            }

            System.Windows.Controls.TreeViewItem TreeViewItem = (ResultsTreeView.Items[0] as System.Windows.Controls.TreeViewItem);
            TreeViewItem.IsSelected = true;
            TreeViewItem.Focus();
        }

        private System.Collections.Generic.Dictionary<string, Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue> GetTestFieldValues(Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Binding i_Binding, out string o_Title, out string o_Description)
        {
            System.Collections.Generic.Dictionary<string, Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue> NamespacedItemValueDictionary = new System.Collections.Generic.Dictionary<string, Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue>();
            o_Title = null;
            o_Description = null;

            foreach (Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field Field in i_Binding.Fields)
            {
                if (Field.Element == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Constants.DEFAULT_TITLE_ELEMENT_NAME)
                {
                    o_Title = "Default title value - " + System.DateTime.Now.Ticks;
                    continue;
                }

                if (Field.Element == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Constants.DEFAULT_DESCRIPTION_ELEMENT_NAME)
                {
                    o_Description = "Default description value - " + +System.DateTime.Now.Ticks;
                    continue;
                }

                Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue FieldValue = null;
                string Value = System.String.Empty;

                if (Field.Array)
                {
                    System.Collections.Generic.List<string> ValueList = new System.Collections.Generic.List<string>();
                    ValueList.Add("Test array item 1 - " + System.DateTime.Now.Ticks);
                    ValueList.Add("Test array item 2 - " + System.DateTime.Now.Ticks);
                    ValueList.Add("Test array item 3 - " + System.DateTime.Now.Ticks);

                    if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.boolean)
                    {
                        ValueList.Add("true");
                        ValueList.Add("false");
                        ValueList.Add("true");
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.datetime)
                    {
                        ValueList.Add(System.DateTime.Now.ToString(Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Constants.DATE_STRING_FORMAT));
                        ValueList.Add(System.DateTime.Now.AddDays(1).ToString(Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Constants.DATE_STRING_FORMAT));
                        ValueList.Add(System.DateTime.Now.AddDays(2).ToString(Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Constants.DATE_STRING_FORMAT));
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.floatingpoint)
                    {
                        ValueList.Add(new Random(System.DateTime.Now.Millisecond).NextDouble().ToString().Substring(0, 8));
                        ValueList.Add(new Random(System.DateTime.Now.Millisecond).NextDouble().ToString().Substring(0, 8));
                        ValueList.Add(new Random(System.DateTime.Now.Millisecond).NextDouble().ToString().Substring(0, 8));
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.none)
                    {
                        ValueList.Add("Test item 1 - " + System.DateTime.Now.Ticks);
                        ValueList.Add("Test item 2 - " + System.DateTime.Now.Ticks);
                        ValueList.Add("Test item 3 - " + System.DateTime.Now.Ticks);
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.number)
                    {
                        ValueList.Add((System.DateTime.Now.Millisecond + 100).ToString());
                        ValueList.Add((System.DateTime.Now.Millisecond + 200).ToString());
                        ValueList.Add((System.DateTime.Now.Millisecond + 300).ToString());
                    }

                    string[] Values = ValueList.ToArray();

                    FieldValue = new Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue
                        (
                        Field.Element,
                        Values
                        );
                }
                else
                {
                    if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.boolean)
                    {
                        Value = "true";
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.datetime)
                    {
                        Value = System.DateTime.Now.ToString(Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Constants.DATE_STRING_FORMAT);
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.floatingpoint)
                    {
                        Value = new Random(System.DateTime.Now.Millisecond).NextDouble().ToString().Substring(0, 8);
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.none)
                    {
                        Value = "Test item - " + System.DateTime.Now.Ticks;
                    }
                    else if (Field.Type == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.Types.number)
                    {
                        Value = System.DateTime.Now.Millisecond.ToString();
                    }
                    
                    FieldValue = new Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue
                        (
                        Field.Element,
                        Value
                        );
                }

                NamespacedItemValueDictionary.Add(Field.Element, FieldValue);
            }

            if (!System.String.IsNullOrEmpty(i_Binding.Title))
            {
                string[] FieldIDs = i_Binding.GetFieldIDsForTitle();
                o_Title = this.ResolveExpressions
                    (
                    i_Binding,
                    i_Binding.Title,
                    FieldIDs,
                    NamespacedItemValueDictionary
                    );
            }

            if (!System.String.IsNullOrEmpty(i_Binding.Description))
            {
                string[] FieldIDs = i_Binding.GetFieldIDsForDescription();
                o_Description = this.ResolveExpressions
                    (
                    i_Binding,
                    i_Binding.Description,
                    FieldIDs,
                    NamespacedItemValueDictionary
                    );
            }

            return NamespacedItemValueDictionary;
        }

        private string ResolveExpressions(Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Binding i_Binding, string i_ExpressionString, string[] i_Elements, System.Collections.Generic.Dictionary<string, Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue> i_NamespacedItemValueDictionary)
        {
            string ResolvedString = i_ExpressionString;

            try
            {
                foreach (string Element in i_Elements)
                {
                    string Value = System.String.Empty;

                    Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.FieldValue FieldValue = i_NamespacedItemValueDictionary[Element];

                    if (System.String.IsNullOrEmpty(FieldValue.Value))
                    {
                        System.Text.StringBuilder StringBuilder = new System.Text.StringBuilder();
                        for (int Index = 0; Index < FieldValue.Values.Length; ++Index)
                        {
                            if (Index > 0)
                                StringBuilder.Append(", ");

                            if (i_Binding.GetField(Element).ContentType == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.ContentTypes.text)
                                Value = MiscHelpers.XMLEncode(FieldValue.Values[Index]);
                            else
                                Value = FieldValue.Values[Index];

                            StringBuilder.Append(Value);
                        }

                        ResolvedString = ResolvedString.Replace
                            (
                            "{" + Element + "}",
                            StringBuilder.ToString()
                            );
                    }
                    else
                    {
                        if (i_Binding.GetField(Element).ContentType == Microsoft.CSA.FeedSync.SimpleFeedBindingsLibrarySL.Field.ContentTypes.text)
                            Value = MiscHelpers.XMLEncode(FieldValue.Value);
                        else
                            Value = FieldValue.Value;

                        ResolvedString = ResolvedString.Replace
                            (
                            "{" + Element + "}",
                            Value
                            );
                    }
                }
            }
            catch (System.Exception Exception)
            {
                System.Diagnostics.Debug.WriteLine("Exception in ResolveExpressions - " + Exception.Message);
            }

            return ResolvedString;
        }

        private void CreateElements(System.Xml.Linq.XDocument i_XDocument, System.Windows.Controls.TreeViewItem i_ParentTreeViewItem)
        {
            System.Collections.Generic.Dictionary<string, string> NamespaceDictionary = new System.Collections.Generic.Dictionary<string, string>();

            var DescendentElements =
                from DescendantXNode in i_XDocument.DescendantNodes()
                where (DescendantXNode.NodeType == System.Xml.XmlNodeType.Element)
                select DescendantXNode;

            m_NamespaceDictionary.Clear();

            foreach (System.Xml.Linq.XElement DescendentElement in DescendentElements)
            {
                var Namespaces = from ElementAttribute in DescendentElement.Attributes()
                                 where (ElementAttribute.IsNamespaceDeclaration == true)
                                 select ElementAttribute;

                foreach (var Namespace in Namespaces)
                {
                    string NamespacePrefix = Namespace.Name.LocalName;
                    string NamespaceURI = Namespace.Value;

                    m_NamespaceDictionary[NamespaceURI] = NamespacePrefix;
                }
            }

            foreach (System.Xml.Linq.XElement XElement in i_XDocument.Elements())
            {
                this.CreateChildElements
                    (
                    XElement,
                    i_ParentTreeViewItem
                    );
            }
        }

        private void CreateChildElements(System.Xml.Linq.XElement i_XElement, System.Windows.Controls.TreeViewItem i_ParentTreeViewItem)
        {
            System.Windows.Controls.ItemCollection ItemCollection = null;

            if (i_ParentTreeViewItem == null)
                ItemCollection = ResultsTreeView.Items;
            else
                ItemCollection = i_ParentTreeViewItem.Items;

            System.Windows.Controls.TreeViewItem TreeViewItem = new System.Windows.Controls.TreeViewItem() { Tag = i_XElement };

            TreeViewItem.Expanded += TreeViewItem_Expanded;
            TreeViewItem.Collapsed += TreeViewItem_Collapsed;
            TreeViewItem.KeyUp += TreeViewItem_KeyUp;

            string ElementName = i_XElement.Name.LocalName;
            if (!System.String.IsNullOrEmpty(i_XElement.Name.NamespaceName))
                ElementName = m_NamespaceDictionary[i_XElement.Name.NamespaceName] + ":" + ElementName;

            TreeViewItem.Header = "<" + ElementName;

            foreach (System.Xml.Linq.XAttribute XAttribute in i_XElement.Attributes())
                TreeViewItem.Header += string.Format(" {0}=\"{1}\"", XAttribute.Name.LocalName, XAttribute.Value);

            var XNodes =
                from XNode in i_XElement.Nodes()
                where (XNode.NodeType == System.Xml.XmlNodeType.Text)
                select XNode;

            if ((XNodes.Count() > 0) || (i_XElement.HasElements))
                TreeViewItem.Header += ">";
            else
                TreeViewItem.Header += "/>";

            foreach (System.Xml.Linq.XText XText in XNodes)
                TreeViewItem.Header += XText.Value;

            if (i_XElement.HasElements)
            {
                foreach (System.Xml.Linq.XElement XElement in i_XElement.Elements())
                {
                    this.CreateChildElements
                        (
                        XElement,
                        TreeViewItem
                        );
                }
            }
            else if (XNodes.Count() > 0)
                TreeViewItem.Header += "</" + ElementName + ">";

            ItemCollection.Add(TreeViewItem);
        }

        void TreeViewItem_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            System.Windows.Controls.TreeViewItem TreeViewItem = sender as System.Windows.Controls.TreeViewItem;

            if (e.Key == System.Windows.Input.Key.Enter)
            {
                TreeViewItem.IsExpanded = !TreeViewItem.IsExpanded;
                e.Handled = true;
            }
        }

        void TreeViewItem_Collapsed(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Windows.Controls.TreeViewItem TreeViewItem = sender as System.Windows.Controls.TreeViewItem;
            System.Xml.Linq.XElement XElement = TreeViewItem.Tag as System.Xml.Linq.XElement;

            if (XElement.HasElements)
            {
                System.Windows.Controls.TreeViewItem ParentTreeViewItem = TreeViewItem.Parent as System.Windows.Controls.TreeViewItem;
                int Index = ParentTreeViewItem.Items.IndexOf(TreeViewItem);
                ParentTreeViewItem.Items.RemoveAt(Index + 1);
            }
        }

        void TreeViewItem_Expanded(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Windows.Controls.TreeViewItem TreeViewItem = sender as System.Windows.Controls.TreeViewItem;
            System.Xml.Linq.XElement XElement = TreeViewItem.Tag as System.Xml.Linq.XElement;

            if (XElement.HasElements)
            {
                System.Windows.Controls.TreeViewItem ParentTreeViewItem = TreeViewItem.Parent as System.Windows.Controls.TreeViewItem;
                int Index = ParentTreeViewItem.Items.IndexOf(TreeViewItem);

                string ElementName = XElement.Name.LocalName;
                if (!System.String.IsNullOrEmpty(XElement.Name.NamespaceName))
                    ElementName = m_NamespaceDictionary[XElement.Name.NamespaceName] + ":" + ElementName;

                ParentTreeViewItem.Items.Insert(Index + 1, (new System.Windows.Controls.TreeViewItem() { Header = "</" + ElementName + ">" }));
            }
        }

        void DisplayTestResults(string i_Header, System.Xml.Linq.XDocument i_XDocument, System.Windows.Controls.TreeViewItem i_ParentTreeViewItem)
        {
            System.Windows.Controls.TreeViewItem TreeViewItem = new System.Windows.Controls.TreeViewItem() { Header = i_Header };
            TreeViewItem.KeyUp += TreeViewItem_KeyUp;

            i_ParentTreeViewItem.Items.Add(TreeViewItem);
            this.CreateElements(i_XDocument, TreeViewItem);
        }

    }
}
